package com.yangwudongxi.sqlloghelper.controller;

import com.yangwudongxi.sqlloghelper.dto.AiAnalysisRequest;
import com.yangwudongxi.sqlloghelper.dto.AiAnalysisResult;
import com.yangwudongxi.sqlloghelper.dto.ApiResponse;
import com.yangwudongxi.sqlloghelper.dto.ErDiagramRequest;
import com.yangwudongxi.sqlloghelper.dto.ErDiagramResult;
import com.yangwudongxi.sqlloghelper.dto.ExecutionPlanStep;
import com.yangwudongxi.sqlloghelper.service.DatabaseQueryService;
import com.yangwudongxi.sqlloghelper.service.DeepSeekService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * AI分析控制器
 *
 * @author 氧屋东西
 */
@Slf4j
@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
@Validated
public class AiAnalysisController {
    
    private final DatabaseQueryService databaseQueryService;
    private final DeepSeekService deepSeekService;
    
    /**
     * AI分析SQL执行计划
     */
    @PostMapping("/analyze")
    public ApiResponse<AiAnalysisResult> analyzeExecutionPlan(@RequestBody @Valid AiAnalysisRequest request) {
        log.info("开始AI分析SQL执行计划：{}", request.getSql().substring(0, Math.min(request.getSql().length(), 100)) + "...");
        
        try {
            // 1. 获取SQL执行计划
            List<ExecutionPlanStep> executionPlan = databaseQueryService.getExecutionPlan(
                    request.getSql(), 
                    request.getDbConfig()
            );
            
            if (executionPlan.isEmpty()) {
                return ApiResponse.error("无法获取SQL执行计划");
            }
            
            // 2. 获取涉及表的建表语句
            Map<String, String> tableCreateStatements = null;
            try {
                tableCreateStatements = databaseQueryService.getTablesCreateStatements(
                        request.getSql(), 
                        request.getDbConfig()
                );
                log.info("成功获取{}个表的建表语句", tableCreateStatements.size());
            } catch (Exception e) {
                log.warn("获取建表语句失败，将仅基于执行计划进行分析", e);
            }
            
            // 3. 调用DeepSeek AI分析（增强版）
            String aiAnalysis = deepSeekService.analyzeExecutionPlan(
                    request.getSql(), 
                    executionPlan, 
                    tableCreateStatements
            );
            
            // 4. 构建结果
            AiAnalysisResult result = AiAnalysisResult.builder()
                    .sql(request.getSql())
                    .executionPlan(executionPlan)
                    .aiAnalysis(aiAnalysis)
                    .build();
            
            return ApiResponse.success("AI分析完成", result);
            
        } catch (Exception e) {
            log.error("AI分析SQL执行计划失败", e);
            return ApiResponse.error("AI分析失败：" + e.getMessage());
        }
    }
    
    /**
     * AI生成数据库表ER图
     */
    @PostMapping("/er-diagram")
    public ApiResponse<ErDiagramResult> generateErDiagram(@RequestBody @Valid ErDiagramRequest request) {
        log.info("开始AI生成ER图，包含{}个SQL语句，{}个查询结果", 
                request.getErData().getSqlStatements().size(),
                request.getErData().getQueryResults().size());
        
        try {
            // 调用DeepSeek AI分析ER图
            ErDiagramResult result = deepSeekService.generateErDiagram(
                    request.getErData(), 
                    request.getDbConfig()
            );
            
            return ApiResponse.success("ER图生成完成", result);
            
        } catch (Exception e) {
            log.error("AI生成ER图失败", e);
            return ApiResponse.error("ER图生成失败：" + e.getMessage());
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ApiResponse<String> health() {
        return ApiResponse.success("AI分析服务正常运行");
    }
}